package algorithm.sort.merge;

import algorithm.sort.SortUtils;

/**
 * @ Author     ：wangyw
 * @ Date       ：Created in 下午12:12 2021/11/18
 * @ Description：归并排序扩展，小和问题
 */
public class SmallSum {

    public static int getSmallSum(Integer[] arr) {
        if (null == arr || arr.length < 2) {
            return 0;
        }
        int n = arr.length;
        return process(arr, 0, n - 1);
    }

    private static int process(Integer[] arr, int l, int r) {
        if (l == r) {
            return 0;
        }
        int m = l + ((r - l) >> 1);
        return process(arr, l, m) + process(arr, m + 1, r) + merge(arr, l, m, r);
    }

    private static int merge(Integer[] arr, int l, int m, int r) {
        int p1 = l, p2 = m + 1, len = r - l + 1, i = 0;
        int ans = 0;
        Integer[] help = new Integer[len];
        while (p1 <= m && p2 <= r) {
            ans += arr[p1] < arr[p2] ? arr[p1] * (r - p2 + 1) : 0;
            help[i++] = arr[p1] < arr[p2] ? arr[p1++] : arr[p2++];
        }
        while (p1 <= m) {
            help[i++] = arr[p1++];
        }
        while (p2 <= r) {
            help[i++] = arr[p2++];
        }
        System.arraycopy(help, 0, arr, l, len);
        return ans;
    }

    public static void main(String[] args) {
        Integer[] arr = /*SortUtils.getRandomIntArr(10, 100)*/new Integer[]{1,2,3};
        int smallSum = getSmallSum(arr);
        System.out.println("smallSum = " + smallSum);
    }
}
